package com.jkj.utils.ueditor.upload;

import com.jkj.utils.ueditor.PathFormat;
import com.jkj.utils.ueditor.define.AppInfo;
import com.jkj.utils.ueditor.define.BaseState;
import com.jkj.utils.ueditor.define.FileType;
import com.jkj.utils.ueditor.define.State;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

public class BinaryUploader {

    public static final State save(HttpServletRequest request, Map<String, Object> conf) {

        boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        if (isAjaxUpload) {
            upload.setHeaderEncoding("UTF-8");
        }
        try {
            MultipartFile upFile = ((MultipartRequest) request).getFile("upfile");
            if (upFile == null) {
                return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
            }
            String savePath = (String) conf.get("savePath");
            String originFileName = upFile.getOriginalFilename();
            String suffix = FileType.getSuffixByFilename(originFileName);

            originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
            savePath = savePath + suffix;
            long size = upFile.getSize();
            long maxSize = ((Long) conf.get("maxSize")).longValue();

            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
            }
            if (size > maxSize) {
                return new BaseState(false, AppInfo.MAX_SIZE);
            }
            savePath = PathFormat.parse(savePath, originFileName);
            String physicalPath = (String) conf.get("rootPath") + savePath;
            File file = new File(physicalPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            upFile.transferTo(file);
            State state = new BaseState(true);
            state.putInfo("size", size);
            state.putInfo("title", file.getName());
            state.putInfo("url", PathFormat.format(savePath));
            state.putInfo("type", suffix);
            state.putInfo("original", originFileName + suffix);
            return state;
        } catch (Exception e) {
            return new BaseState(false, AppInfo.IO_ERROR);
        }
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);

        return list.contains(type);
    }
}
